package xyz.longicorn.driver.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.lang.UUID;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.longicorn.driver.config.annotation.OperationLog;
import xyz.longicorn.driver.dto.ApiResult;
import xyz.longicorn.driver.service.EmailService;
import xyz.longicorn.driver.util.RedisUtil;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class CodeController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private EmailService emailService;

    @SaCheckRole("op") // 访问此方法必须有op角色
    @OperationLog("产生一个唯一的验证码id")
    @RequestMapping("/code-id")
    public String createCodeId() {
        return UUID.fastUUID().toString();
    }

    @RequestMapping("/code")
    @SneakyThrows
    public void createImage(String id, HttpServletResponse response) {
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
        final ServletOutputStream os = response.getOutputStream();
        String code = lineCaptcha.getCode();
        // 使用id保存对应的验证码
        stringRedisTemplate.opsForValue().set("code:" + id, code, 180, TimeUnit.SECONDS);
        System.out.println("当前验证码:" + code);
        lineCaptcha.write(os);
    }

    @RequestMapping("/verify")
    @OperationLog("检查验证码是否正确")
    public String verify(String id, String code) {
        String key = "code:" + id;
        String code1 = stringRedisTemplate.opsForValue().get(key);
        if (code1 != null && code1.equals(code)) {
            // 使原始验证码失效
            stringRedisTemplate.delete(key);
            return "true";
        }
        return "false";
    }

    @RequestMapping("/create")
    public ApiResult createBase64Code() {
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
        String code = lineCaptcha.getCode();
        String id = UUID.fastUUID().toString();
        // 使用id保存对应的验证码
        stringRedisTemplate.opsForValue().set("code:" + id, code, 180, TimeUnit.SECONDS);
        // 获取验证码的base64
        String image = lineCaptcha.getImageBase64Data();
        Map<String, String> data = new HashMap<>();
        data.put("id", id);
        data.put("image", image);
        return ApiResult.success(data);
    }

    @Value("${application.email-content}")
    private String codeTemplate;

    @RequestMapping("/send-code")
    public ApiResult sendVerifyCode(String email) {
        RandomGenerator generator = new RandomGenerator("0123456789", 6);
        String code = generator.generate(); // 产生验证码
        // 发送验证码
        try {
            emailService.sendHTML(email, codeTemplate.replace("$code", code), "验证码");
        } catch (MessagingException e) {
            return ApiResult.error(1,"发送验证码失败");
        }
        // 记录该邮箱的验证码
        stringRedisTemplate.opsForValue().set("email:code:" + email, code,
                180, TimeUnit.SECONDS);
        return ApiResult.success(true);
    }
}
